package com.mdnote.practice.dp;

import sun.reflect.generics.tree.Tree;

/**
 * @author Rhythm-2019
 * @version 1.0
 * @date 2020/9/22
 * @description 打家劫舍 III
 */
public class LeetCode337 {

    public static void main(String[] args) {
        LeetCode337 leetCode337 = new LeetCode337();
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.right = new TreeNode(3);
        root.right.right = new TreeNode(1);
        int rob = leetCode337.rob(root);
        System.out.println(rob);
    }

    /**
     * 树的动态规划其实和数组基本相似，只是我们要边遍历数组边进行推到
     * 1. 重复子问题：
     * 2. 缓存中间结果
     * 3. DP公式：dp[i][0] = Max(dp[i - 1][0], dp[i - 1][1])
     *           dp[i][0] = dp[i - 1][0] + nums[i]
     *
     * @param root
     * @return
     */
    public int rob(TreeNode root) {


        if (root == null) {
            return 0;
        }
        int[] res = dfs(root);
        return Math.max(res[0], res[1]);
    }

    private int[] dfs(TreeNode node) {

        // 使用后序遍历对节点进行遍历
        // 自下而上 - 后序遍历，自顶向下 - 前序遍历

        // Terminator
        if (node == null) {
            return new int[]{0, 0};
        }

        // split big problem
        int[] left = dfs(node.left);
        int[] right = dfs(node.right);

        // merge
        int[] dp = new int[2];
        dp[0] = left[1] + right[1] + node.val;
        // 这里应该考虑四种情况，左边偷or不偷  右边偷or不偷
        dp[1] = Math.max(left[1] + right[1], left[0] + right[0]);

        return dp;
    }


    public static class TreeNode {
         int val;
         TreeNode left;
         TreeNode right;
         TreeNode(int x) { val = x; }
    }
}
